import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    public Runnable runnable;
    //使用绝对的时间戳
    public long time;

    public MyTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }

    @Override
    public int compareTo(MyTask o){
        return (int)(this.time-o.time);
    }
}

class MyTimer{
    //这个结构，带有优先级的阻塞队列，核心数据结构
    private PriorityBlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();
    //创造一个锁对象
    private Object locker=new Object();

    public void schedule(Runnable runnable,long delay){
        MyTask myTask=new MyTask(runnable,delay);
        queue.put(myTask);
        synchronized (locker){
            locker.notify();
        }
    }

    public MyTimer(){
        Thread t=new Thread(()->{
            while (true){
                try {
                    //阻塞队列，只有阻塞的入队和阻塞的出队列，没有阻塞的查看队首元素
                    MyTask myTask=queue.take();
                    long curTime=System.currentTimeMillis();
                    if(myTask.time<=curTime){
                        //时间到了，可以执行任务
                        myTask.runnable.run();
                    }else{
                        //时间没到
                        //将取出的任务重新赛会队列中
                        queue.put(myTask);
                        synchronized (locker){
                            locker.wait(myTask.time-curTime);
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class demo02 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello4");
            }
        },4000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        },1000);

        System.out.println("hello0");
    }
}
